//
//  CZHomeController.swift
//  weibo27
//
//  Created by mac on 16/4/16.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 原创微博的重用表示
let statusNormalID = "statusNormalID"
//// 转发微博的重用表示
let statusRetweetedID = "statusRetweetedID"

class CZHomeController: CZVistorTableController {

    var dataList = [CZUserStatus]()
    
    private lazy var userStatus: CZUserStatusViewModel = CZUserStatusViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if !CZUserAccountViewModel.shareModel.userLogin{
            
            visitorView?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            
        }else{
            //隐藏顶部视图上的两个按钮
            navigationItem.leftBarButtonItem = nil
            
            navigationItem.rightBarButtonItem = nil
        }
        
         prepareForTableView()
        
        loadStatuses()
        //发送微博之后，要接收并且刷新数据
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadSendStatus", name: "sendStatusToWeibo", object: nil)
        
        //点击图片之后 注册监听事件 
        NSNotificationCenter.defaultCenter().addObserverForName("WBStatusSeletedPhoneNotification", object:nil , queue:nil) { [weak self](notify) -> Void in
            
//            处理事情
//            print("接收到通知\(notify)")
            
            guard let urls = notify.userInfo?[WBStatusSeletedPhotoURLKey] as? [NSURL] else{
                return
            }
            
            guard let indexPath = notify.userInfo?[WBStatusSeletedPhotoIndexPathKey] as? NSIndexPath else{
                return
            }
            
            //将收到的通知发送出去
            let vc = CZPictureBrowerView(urls: urls, currentIndexPath: indexPath)
            
            //自定义转场动画
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            //设置代理
            vc.transitioningDelegate = self?.pictureAnimator
            //modal展现
            self?.presentViewController(vc, animated: true, completion: nil)
        }
    
    }
    
    //移除通知
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //微博发送后要刷新微博的最新状态
    @objc func reloadSendStatus(){
        
        //刷新数据
        loadStatuses()
        
//        dispatch_async(dispatch_get_main_queue()) { () -> Void in
//            SVProgressHUD.showInfoWithStatus("发送成功")
//        }
    }
    
    func prepareForTableView(){
        
        // 注册cell 使用自己的cell注册
        tableView.registerClass(CZStatusRetweeted.self, forCellReuseIdentifier: statusRetweetedID)
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: statusNormalID)
        
        // 指定的临时行高  使用它的时候，控件的底部要指定具体的参照
        tableView.estimatedRowHeight = 400
        // 取消分割线
        tableView.separatorStyle = .None
        
        self.refreshControl?.beginRefreshing()
        // 添加下拉刷新控件
        refreshControl = CZRefreshControl()
        // 下拉刷新事件 它的事件的改变是通过ValueChanged来实现的
        refreshControl?.addTarget(self, action: "loadStatuses", forControlEvents: UIControlEvents.ValueChanged)

       
        //将创建的指示器添加进去
        tableView.tableFooterView = pullupView
    }
    
    
    //加载微博数据类型
  @objc private func loadStatuses(){
    
    //在数据没有请求回来的时候，显示动画效果
      refreshControl?.beginRefreshing()

        userStatus.loadUserStatus(isPullup: pullupView.isAnimating()) { (isSuccess) -> () in
            
            //停止下拉刷新数据
            self.refreshControl?.endRefreshing()
            //关闭上拉刷新数据
            self.pullupView.stopAnimating()
            
            if !isSuccess {
                print("获取用户模型数据出错")
                return
            }
//            print(self.userStatus.statusList)
            //刷新数据
            self.tableView.reloadData()
        }
       
    }
    
    //懒加载上拉刷新控件
    private lazy var pullupView:UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        //单独设置指示器的颜色
        indicator.color = UIColor.redColor()
        
        return indicator
    }()
    
    private lazy var pictureAnimator:CZPictureAnimator = CZPictureAnimator()
    
}

// MARK: 数据源方法
extension CZHomeController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userStatus.statusList.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let vm = userStatus.statusList[indexPath.row]
        
        //多态的使用，父类的对象指向子类的对象
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellId, forIndexPath: indexPath) as! CZStatusCell
        
        //判断是否为最后一条数据，如果是最后一条就加载
        if indexPath.row == userStatus.statusList.count - 1 && !pullupView.isAnimating() {
            print("应该上拉刷新了")
            pullupView.startAnimating()
           
            //开始刷新数据 下拉
            loadStatuses()
        }
        
        cell.statusViewModel = vm

        return cell
    }
    
    // 返回行高
    ///
    /// - parameter tableView: tableView description
    /// - parameter indexPath: indexPath description
    ///
    /// - returns: 返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

         //使用懒加载的加载行高 
        return userStatus.statusList[indexPath.row].rowHeight

    }
}




























